package net.unix8.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {
    public static void main(String[] args) throws Exception {
    	//connect("192.168.0.100",4040);
    }
	private String cmd;
	private ChannelId channel;
    private ClientHandler clientHandler;
    private String hostString;
    private int id;
    public Client(ChannelId channelId, String cmd,String host, int id){
		this.cmd = cmd;	
		this.channel = channelId;
		this.hostString = host;
		this.id = id;
		clientHandler = new ClientHandler(channel,cmd, hostString,id);

    }  
    public   void connect(String host, int port) throws Exception {
         EventLoopGroup workerGroup = new NioEventLoopGroup();
         try {
             Bootstrap b = new Bootstrap(); // (1)
             b.group(workerGroup); // (2)
             b.channel(NioSocketChannel.class); // (3)
             b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
             b.handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(clientHandler);
                 }
             });
             clientHandler.setIp(host);
             // Start the client.
	         System.out.print("Start the client");
	         System.out.flush();
             ChannelFuture f = b.connect(host, port).sync(); // (5)
             // Wait until the connection is closed.
             f.channel().closeFuture().sync();
	         System.out.print("End the client");
	         System.out.flush();
         } finally {
             workerGroup.shutdownGracefully();
         }
    }
}